package cn.echisan.springbootjwtdemo.utils;

import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * Created by echisan on 2018/6/23
 */
public class JwtTokenUtils {
    public static final String TOKEN_PREFIX = "Bearer ";
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtils.class);
    private static final String SECRET = "jwtsecretdemo";
    private static final String ISS = "echisan";

    // 角色的key
    private static final String ROLE_CLAIMS = "rol";

    // 过期时间是3600秒，即是1个小时
    private static final long EXPIRATION = 60000L;

    // 选择了记住我之后的过期时间为7天
    private static final long EXPIRATION_REMEMBER = 1000 * 60 * 60 * 24 * 7L;
    private final static SecretKey key = Jwts.SIG.HS512.key()
            .build();

    // 创建token
    public static String createToken(String username, String role, boolean isRememberMe) {
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        ClaimsBuilder claims = Jwts.claims();
        claims.add(ROLE_CLAIMS, role);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setClaims(claims.build())
                .setIssuer(ISS)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .compact();
    }

    // 从token中获取用户名
    public static String getUsername(String token) {
        return getTokenBody(token).getSubject();
    }

    // 获取用户角色
    public static String getUserRole(String token) {
        return (String) getTokenBody(token).get(ROLE_CLAIMS);
    }

    // 获取用户过期时间,如果想做距离过期前多少秒刷新,可以用这个函数
    public static Date getExpiration(String token) {
        return getTokenBody(token).getExpiration();
    }

    // 是否已过期
    public static boolean isExpiration(String token) {
        try {
            getTokenBody(token);
            return false;
        } catch (ExpiredJwtException e) {
            // token过期
            return true;
        } catch (SignatureException e) {
            // 校验签名失败
            return true;
        } catch (MalformedJwtException e) {
            // 解码jwt认证token时失败
            return true;
        }
    }

    private static Claims getTokenBody(String token) {
        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}
